package com.rzpt.controller;


import com.rzpt.pojo.impl.Result;
import com.rzpt.pojo.impl.User;
import com.rzpt.serverice.UserService;
import com.rzpt.utils.JwtUtil;
import com.rzpt.utils.MD5Util;
import com.rzpt.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@RestController
@Validated
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /*
     * 注册
     *
     */
    @PostMapping("/register")
    public Result register(String account, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
//        信息合法验证
        if (account != null && account.length() >= 6 && account.length() <= 18 &&
                password.length() >= 6 && password.length() <= 18
        ) {
//        查询用户
            User userReg = userService.findByAccount(account);
            if (userReg == null) {
                userService.register(account, MD5Util.md5(password));
                return Result.success();
            } else {
//        注册
                return Result.error("账号重复");
            }
        } else {
            return Result.error("账号参数不合法");
        }
    }

    /*
     * 登录
     *
     */
    @PostMapping("/login")
    public Result login(String account, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
//        登录参数验证
        if (account != null && account.length() >= 6 && account.length() <= 18 &&
                password.length() >= 6 && password.length() <= 18) {
            User userlogin = userService.findByAccount(account);
            if (userlogin == null) {
//                账户不存在
                return Result.error("登录失败");
            } else {
//                账户存在，判断密码
                if (MD5Util.md5(password).equals(userlogin.getPassword())) {
//                    密码正确，返回token
                    Map<String, Object> claims = new HashMap<>();
                    claims.put("account", userlogin.getAccount());
                    claims.put("password", userlogin.getPassword());
                    return Result.success(JwtUtil.genToken(claims));
                } else {
                    return Result.error("登录失败");
                }
            }
        }
        return Result.error("登录失败，检查合法性");
    }

    /*
     * 获取用户信息
     *
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
//        Map<String, Object> map = JwtUtil.paseJWT(token);
//        String username = (String) map.get("account");
        Map<String, Object> map = ThreadLocalUtil.get();
        return Result.success(userService.findByAccount((String) map.get("account")));
    }

    /*
     * 修改用户信息
     *
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.updateUser(user);
        return Result.success();
    }

    /*
     * 修改头像
     *
     */
    @PatchMapping("/updateH")
    public Result updateHeaderImg(@RequestParam @URL String headerUrl) {
        userService.updateHeaderImg(headerUrl);
        return Result.success();
    }

    /*
     * 修改密码
     *
     */
    @PatchMapping("/updatePwd")
    public Result updataPwd(@RequestParam Map<String, String> parms) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String oldPwd = parms.get("old_pwd");
        String newPwd = parms.get("new_pwd");
        String rePwd = parms.get("re_pwd");
        if (newPwd.length() < 6
                || newPwd.length() > 18) {
            return Result.error("密码必须为6~18位");
        }
//        if (!StringUtils.hasLength(oldPwd)
//                || !StringUtils.hasLength(newPwd)
//                || !StringUtils.hasLength(rePwd)) {
//            return Result.error("参数不合法");
//        }
        Map<String, Object> map = ThreadLocalUtil.get();
        User user = userService.findByAccount((String) map.get("account"));
        if (user.getPassword().equals(MD5Util.md5(oldPwd))) {
            if (!newPwd.equals(rePwd)) {
                return Result.error("两次输入的密码不一致");
            }
            userService.updatePwd(MD5Util.md5(newPwd), (String) map.get("account"));
            return Result.success();
        } else {
            return Result.error("新密码与旧密码不一致");
        }
    }
}
